package cn.alone.basic.util;

import cn.alone.user.domain.Logininfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.http.HttpServletRequest;

/**
 * 工具类,获取请求头中的登录人信息
 * @author lanan
 */
public class LoginContext {
    /**
     * 获取当前登录人
     * @param request
     * @return
     */
    public static Logininfo getCurrentLogininfo(HttpServletRequest request){
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)){
            //1.先得到Spring容器
            WebApplicationContext webApplicationContext =
                    WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            //2.通过容器获取容器中的对象
            RedisTemplate redisTemplate = (RedisTemplate) webApplicationContext.getBean("redisTemplate");
            Object loginTmp = redisTemplate.opsForValue().get(token);
            if(loginTmp != null){
                return (Logininfo) loginTmp;
            }
        }
        return null;
    }
}
